﻿using System;
using System.Linq;
using System.Text;
// Krzysztof Heim
// pktools.codeplex.com

namespace PKTools
{
    public static class ObjectExtender
    {
        public static bool In<T>(this T obj, params T[] objs)
        {
            return objs.Contains(obj);
        }

        public static bool Between(this int value, int begin, int end)
        {
            return value >= begin && value <= end;
        }

        public static int SafeToInt(this string value, int defaultValue)
        {
            int
                n;

            return Int32.TryParse(value, out n) ? n : defaultValue;
        }

        public static T IfNull<T>(this object value, T defaultValue)
        {
            if (value == null)
                return defaultValue;

            return (T)value;
        }

        public static T IfNull<T>(this object value, Func<object, T> notNullF, T defaultValue)
        {
            return value == null ? defaultValue : notNullF(value);
        }

        /// <summary>
        /// Cuts part of string from - to given position
        /// </summary>
        /// <param name="from">from position</param>
        /// <param name="to">to position</param>
        public static string Cut(this string value, int from, int to)
        {
            return value.Substring(from, to - from);
        }

        public static string ToDetailString(this DateTime value)
        {
            return value.ToString("yy-MM-dd HH:mm:ss.fff");
        }

        public static string ToDetailString(this TimeSpan timeSpan)
        {
            return new DateTime(timeSpan.Ticks).ToShortTimeString();
        }

        /// <summary>
        /// Case insensitive string replace
        /// </summary>
        /// <param name="a">search for</param>
        /// <param name="b">replace with</param>
        public static string ReplaceCI(this string value, string a, string b)
        {
            if (value == null)
                return null;

            if (string.IsNullOrEmpty(a))
                return value;

            var
                builder = new StringBuilder();
            int
                index = 0;

            for (; ; )
            {
                int
                    i = value.IndexOf(a, index, StringComparison.OrdinalIgnoreCase);

                if (i == -1)
                    break;

                builder.Append(value, index, i - index);
                builder.Append(b);

                index = i + a.Length;
            }

            builder.Append(value, index, value.Length - index);

            return builder.ToString();
        }
    }
}
